/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ResultadosProfesor.java
 *
 * Created on 12-ene-2012, 19:39:25
 */
package occho.view;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.html.HTMLDocument.Iterator;
import javax.swing.tree.*;
import occho.model.*;
import occho.view.resources.Messages;

/**
 *
 * @author Juan Antonio
 */
public class ResultadosProfesorFrame extends javax.swing.JInternalFrame implements Internacionalizable {

    FachadaVerResultados fachadaVerResultado;
    Usuario usuario;
    
    /** Creates new form ResultadosProfesor
     * @param user 
     */
    public ResultadosProfesorFrame(Usuario user) {
        initComponents();
        this.usuario=user;
        setLenguaje(); 
        this.fachadaVerResultado=new FachadaVerResultados(user); 
        this.resultadosTable.setVisible(false);
        cargarArbol();
    
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        arbolScrollPane = new javax.swing.JScrollPane();
        testTree = new javax.swing.JTree();
        tablaScrollPane = new javax.swing.JScrollPane();
        resultadosTable = new javax.swing.JTable();

        setClosable(true);
        setName("Form"); // NOI18N

        arbolScrollPane.setName("arbolScrollPane"); // NOI18N

        testTree.setName("testTree"); // NOI18N
        testTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                testTreeValueChanged(evt);
            }
        });
        arbolScrollPane.setViewportView(testTree);

        tablaScrollPane.setName("tablaScrollPane"); // NOI18N

        resultadosTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Alumno", "Nota"
            }
        ));
        resultadosTable.setName("resultadosTable"); // NOI18N
        tablaScrollPane.setViewportView(resultadosTable);
        resultadosTable.getColumnModel().getColumn(0).setPreferredWidth(110);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(arbolScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tablaScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 487, Short.MAX_VALUE)
                .addGap(22, 22, 22))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tablaScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                    .addComponent(arbolScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void testTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_testTreeValueChanged
    DefaultMutableTreeNode selectedNode = 
            (DefaultMutableTreeNode) testTree.getLastSelectedPathComponent();
    switch (selectedNode.getLevel()) {
        case 2: Test test = (Test) selectedNode.getUserObject();
                try {
                        HashMap<Usuario, Test> mapa =this.fachadaVerResultado.seleccionarTestAlumnos(test);
                        mostrarNombres(mapa);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(ResultadosProfesorFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(ResultadosProfesorFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
        default: break;       
    }
}//GEN-LAST:event_testTreeValueChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane arbolScrollPane;
    private javax.swing.JTable resultadosTable;
    private javax.swing.JScrollPane tablaScrollPane;
    private javax.swing.JTree testTree;
    // End of variables declaration//GEN-END:variables

    private void cargarArbol() {
        DefaultMutableTreeNode top =new DefaultMutableTreeNode("Asignaturas");
        createNodes(top);
        DefaultTreeModel modelo = new DefaultTreeModel(top);
        this.testTree.setModel(modelo);
        this.testTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    }
    
    private void createNodes(DefaultMutableTreeNode top) {
        DefaultMutableTreeNode asignaturaNode = null;
        DefaultMutableTreeNode testNode = null;
        
        for (Asignatura asig : this.usuario.getAsignaturas()) {
            asignaturaNode = new DefaultMutableTreeNode(asig);
            top.add(asignaturaNode);
            
            for (Test t : asig.getTests()) {
                testNode = new DefaultMutableTreeNode(t);
                asignaturaNode.add(testNode);
            }
        }
    }
    
    /**
     * Muestra los resultados en la tabla.
     * @param mapa
     */
    public void  mostrarNombres(HashMap<Usuario, Test> mapa){
        if(!mapa.isEmpty()){
            this.resultadosTable.setVisible(true);
            DefaultTableModel modelo=new DefaultTableModel();
            this.resultadosTable.setModel(modelo);
            modelo.addColumn("Alumno");
            modelo.addColumn("Nota");
            
            java.util.Iterator<Entry<Usuario, Test>> it=mapa.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry e = (Map.Entry) it.next();
                Usuario u=(Usuario) e.getKey();
                Test t=(Test) e.getValue();
                Object[] fila = new Object[2];
                fila[0]=new String(u.getNombre()+" "+u.getApellidos());
                fila[1]=new String(t.getAciertos()+"/"+t.getNumPreguntas()+" ("+t.getNota()+")");
                modelo.addRow(fila);
            } 
        }
        else{
            this.resultadosTable.setVisible(false);
            JOptionPane.showMessageDialog(null, "Ningun alumno ha realizado el test");
            
        }
        /*
        
        
        modelo.addRow(new Object[0] );
        this.resultadosTable.setValueAt(lista.get(0).getNombre(), 0, 0);
        this.resultadosTable.setValueAt(lista.get(1).getNombre(), 1, 0);*/
    }

    public void setLenguaje() {
        setTitle(Messages.getString("Form.title", Messages.BUNDLE_NAME_RESULTADOS_PROFESOR));
        resultadosTable.getColumnModel().getColumn(0).setHeaderValue(Messages.getString("tabla.alumno", Messages.BUNDLE_NAME_RESULTADOS_PROFESOR));
        resultadosTable.getColumnModel().getColumn(1).setHeaderValue(Messages.getString("tabla.nota", Messages.BUNDLE_NAME_RESULTADOS_PROFESOR));
        pack();
    }
}
